import tkinter as tk
from PIL import Image, ImageTk
from pathlib import Path
from typing import Dict, Optional


class IconManager:
    def __init__(self):
        self.icons: Dict[str, tk.PhotoImage] = {}
        self.default_icons: Dict[str, str] = {
            "folder": "default_folder_icon",
            "tool": "default_tool_icon",
            "plugin": "default_plugin_icon",
            "error": "default_error_icon",
            "warning": "default_warning_icon",
            "info": "default_info_icon"
        }
        self.resources_path = Path("resources/icons")
        self._load_default_icons()

    def _load_default_icons(self):
        """加载默认图标（占位符实现）"""
        # 这里可以使用简单的占位图标或从资源文件加载
        for icon_name in self.default_icons:
            self.icons[icon_name] = self._create_placeholder_icon()

    def _create_placeholder_icon(self, size=(16, 16), color="gray"):
        """创建占位图标"""
        from tkinter import Canvas
        image = Image.new("RGBA", size, (0, 0, 0, 0))
        return ImageTk.PhotoImage(image)

    def load_icon(self, icon_name: str, icon_path: Optional[str] = None) -> bool:
        """从文件加载图标"""
        try:
            if icon_path is None:
                icon_path = self.resources_path / f"{icon_name}.png"

            if not icon_path.exists():
                return False

            image = Image.open(icon_path)
            self.icons[icon_name] = ImageTk.PhotoImage(image)
            return True
        except Exception as e:
            print(f"Failed to load icon {icon_name}: {str(e)}")
            return False

    def get_icon(self, icon_name: str) -> tk.PhotoImage:
        """获取图标"""
        if icon_name in self.icons:
            return self.icons[icon_name]

        # 尝试加载图标文件
        if self.load_icon(icon_name):
            return self.icons[icon_name]

        # 返回默认图标
        default_type = icon_name.split("_")[0] if "_" in icon_name else "tool"
        return self.icons.get(self.default_icons.get(default_type, "tool"))

    def add_icon(self, icon_name: str, image: Image.Image) -> None:
        """添加内存中的图标"""
        self.icons[icon_name] = ImageTk.PhotoImage(image)

    @property
    def folder(self) -> tk.PhotoImage:
        """获取文件夹图标"""
        return self.get_icon("folder")

    @property
    def tool(self) -> tk.PhotoImage:
        """获取工具图标"""
        return self.get_icon("tool")

    @property
    def plugin(self) -> tk.PhotoImage:
        """获取插件图标"""
        return self.get_icon("plugin")

    def clear_cache(self):
        """清除图标缓存"""
        self.icons.clear()
        self._load_default_icons()